import * as echarts from '../../ec-canvas/echarts';
const app = getApp()
const utils = require('../../utils/util.js')
let chartInstance;
function setOption(chart, options) {
  const option = {
    title: {
      left: 24,
      text: '巴杀温度监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      },
      subtext: '温度（单位℃）',
      subtextStyle: {
        color: '#666666',
        fontSize: 11
      }
    },
    legend: {
      right: 24,
      data: options.legend
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return (params[0].data[0] + '\n' +"温度:" +  params[0].data[1] + "℃");
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    yAxis: {
      show: false,
      boundaryGap: [0, '100%'],
    },
    series: options.series, 
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 100,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ]
  };
  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    no: '',  // 设备号
    basaName: '',
    ndsName: '',
    deviceId : 0,
    beginTime: '', // 开始日期
    endTime: '', // 结束日期
    dataList: []
  },

  handleBeginTimeChange(e) {
    this.setData({
      beginTime: e.detail
    })
    this.handleTimeChange()
  },

  handleEndTimeChange(e) {
    this.setData({
      endTime: e.detail
    })
    this.handleTimeChange()
  },

  handleTimeChange() {
    let that = this;
    const { beginTime, endTime } = this.data
    if (beginTime && endTime) {
      let queryParams = {
        "deviceId" : this.data.deviceId,
        "beginTime" : beginTime + " 00:00:00",
        "endTime" : endTime + " 23:59:59"
      };
      utils.promiseGet('/wx/device/basachannel/getTempData', queryParams).then(function(res){
        let todayData = {
          name : "温度",
          data: [],
          type: 'line',
          areaStyle: {}
        };
        let hourArr = [];
        if (res.code == 200 && res.data) {
          if (res.data.list.length > 0) {
            for (var i = 0; i < res.data.list.length; i++) {
              let tempTime = res.data.list[i].createTime;
              let tempTimeFormat = that.splittime(tempTime);
              if (hourArr[tempTimeFormat] != null) {
                hourArr[tempTimeFormat].push(res.data.list[i]);
              } else {
                hourArr[tempTimeFormat] = new Array();
                hourArr[tempTimeFormat].push(res.data.list[i]);
              }
            }
          }
        }

        var todayArr = [];
        let range = that.getDayRange(beginTime, endTime);
        for(let i = 0; i < range.length; i++) {
          let index = parseInt(range[i]);
          if (hourArr[index]) {
            for(let j=0; j < hourArr[index].length;j++) {
              let temp = hourArr[index][j].content;
                temp = parseFloat(temp);
              var item = new Array(hourArr[index][j].createTime, temp);
              todayArr.push(item);
            }
          } else {
            let year = range[i].substr(0, 4);
            let month = range[i].substr(4, 2);
            let day = range[i].substr(6, 2);
            let hour = range[i].substr(8, 2);
            todayArr.push(new Array(year + "-" + month + "-" + day + " " + hour + ":12:12", 0));
            todayArr.push(new Array(year + "-" + month + "-" + day + " " + hour + ":50:12", 0));
          }
        }
        todayData.data = todayArr;

        if (todayData.data.length == 0) {
          todayData.data = new Array(new Array(utils.formatTime(new Date()), 0));
        }
        var series = new Array(todayData);
        console.log(series);
        if (chartInstance) {
          setOption(chartInstance, {
            series
          });
        }
      }).catch(function(e){
        console.log(e);
      });
    }
    console.log(beginTime, endTime)
  },

  initChart: function (series) {
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOption(chart, {
        series
      });
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;
      chartInstance = chart;
      this.setData({
        isDisposed: false
      });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      no : options.dceNo || '',
      deviceId : options.deviceId || 0,
      basaName: options.basaName || '',
      ndsName : options.ndsName || '',
    });
    this.ecComponent = this.selectComponent('#mychart-dom-line')
    this.loadInnerChart();
    this.loadList();

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  loadInnerChart : function() {
    let that = this;
    utils.promiseGet('/wx/device/basachannel/getTempData', {"deviceId" : this.data.deviceId}).then(function(res){
      let todayData = {
        name : "温度",
        data: [],
        //smooth: true,
        type: 'line',
        areaStyle: {}
      };
      let hourArr = [];
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          for (var i = 0; i < res.data.list.length; i++) {
            let tempTime = res.data.list[i].createTime;
            let tempTimeFormat = that.splittime(tempTime);
            if (hourArr[tempTimeFormat] != null) {
              hourArr[tempTimeFormat].push(res.data.list[i]);
            } else {
              hourArr[tempTimeFormat] = new Array();
              hourArr[tempTimeFormat].push(res.data.list[i]);
            }
          }
        }
      }
      var todayArr = [];
      let range = that.getDayRange(that.getToday(), that.getToday());
      for(let i = 0; i < range.length; i++) {
        let index = parseInt(range[i]);
        if (hourArr[index]) {
          for(let j=0; j < hourArr[index].length;j++) {
            let temp = hourArr[index][j].content;
              temp = parseFloat(temp);
            var item = new Array(hourArr[index][j].createTime, temp);
            todayArr.push(item);
          }
        } else {
          let year = range[i].substr(0, 4);
          let month = range[i].substr(4, 2);
          let day = range[i].substr(6, 2);
          let hour = range[i].substr(8, 2);
          todayArr.push(new Array(year + "-" + month + "-" + day + " " + hour + ":12:12", 0));
          todayArr.push(new Array(year + "-" + month + "-" + day + " " + hour + ":50:12", 0));
        }
      }
      todayData.data = todayArr;
      if (todayData.data.length == 0) {
        todayData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      var series = new Array(todayData);
      console.log(series);
      that.initChart(series);
    }).catch(function(e){
      console.log(e);
    });
  },
  loadList: function () {
    let that = this;
    let getListParams = {
      "deviceId": that.data.deviceId,
      "page": 1,
      "pageSize": 5,
    };
    utils.promiseGet('/wx/device/basachannel/getList', getListParams).then(res => {
      let list = [];
      if (res.code == 200) {
        let result = res.data;
        if (result.rows.length > 0) {
          for (let i = 0; i < result.rows.length; i++) {
            let val = result.rows[i].keywordText || result.rows[i].keyword;
                val = val + " " + result.rows[i].content;
            let itemRow = {
              "time" : result.rows[i].createTime,
              "value" : val
            };
            list.push(itemRow);
          }
        }
      }
      this.setData({
        dataList: list
      });
    }).catch(e => {
      console.log(e);
    });
  },
  toPageLog(event) {
    let that = this;
    var jumpUrl = '/pages/record/basaLog?deviceId=' + that.data.deviceId;
    wx.navigateTo({
      url: jumpUrl
    });
  },
  refreshData(event){
    let that = this;
    const { beginTime, endTime } = this.data
    if (!beginTime && !endTime) {
      this.loadInnerChart();
    }
    this.loadList();
  },
  splittime(str) {
    var removeGua = str.replace(/-/g, '');
    var strs= new Array(); //定义一数组
    strs=removeGua.split(" "); //字符分割
    let yyyymmdd = strs[0];
    var hoursf = new Array();
    hoursf = strs[1].split(":");
    return  parseInt(yyyymmdd + '' + hoursf[0]);
  },
  getYester() {
    var day1 = new Date();
    day1.setDate(day1.getDate() - 1);
    var year = day1.getFullYear();
    var month = day1.getMonth()+1; //获取当前月份 
    var day = day1.getDate(); //获取当前日(1-31)  
    var nextDay = year + "-" + ((month < 10) ? ('0'+month) : month)  + "-" 
      + ((day < 10) ? ('0'+day) : day);
    return nextDay;
  },
  getToday() {
    var day1 = new Date();
    var year = day1.getFullYear();
    var month = day1.getMonth()+1; //获取当前月份 
    var day = day1.getDate(); //获取当前日(1-31)  
    var nextDay = year + "-" + ((month < 10) ? ('0'+month) : month)  + "-" 
      + ((day < 10) ? ('0'+day) : day);
    return nextDay;
  },
  getDayRange(beginDay, endDay){
    let result = [];
    if (beginDay == endDay) {
      result = this.getDayRangeByHour(beginDay);
      return result;
    }
    var nextDay = beginDay;
    do {
      let temp = this.getDayRangeByHour(nextDay);
      result = result.concat(temp);
      var date= new Date(Date.parse(nextDay.replace(/-/g,   "/"))); //转换成Data();
      date.setDate(date.getDate() + 1);
      var year = date.getFullYear();
      var month = date.getMonth()+1; //获取当前月份 
      var day = date.getDate(); //获取当前日(1-31)  
      var nextDay = year + "-" + ((month < 10) ? ('0'+month) : month)  + "-" 
        + ((day < 10) ? ('0'+day) : day);
    } while(nextDay != endDay);
    let temp = this.getDayRangeByHour(nextDay);
    result = result.concat(temp);
    return result;
  },
  getDayRangeByHour(yygmmgdd){
    var removeGua = yygmmgdd.replace(/-/g, '');
    var arr = new Array();
    for(let i=0;i<24;i++) {
      let hour = i;
      if (i<10) {
        hour = '0' + '' + i;
      }
      arr.push(removeGua + '' + hour);
    }
    return arr;
  }
})